import pinia from "@/stores/index"
import { appStore } from "@/stores/appStore/appStore"
import { userStore } from "@/stores/userStore/userStore"
import {
	isEmpty,
	isNotEmpty,
	deepClone,
	UUIDGeneratorBrowser
} from '@/util/localTool'
import qs from 'qs'
//import logYunConsole from '@/util/logYunConsole.js'
const app = appStore(pinia)
const user = userStore(pinia)
const setUrl = function (obj: { url: string, params?: object }): RequestInfo {
	let str = ''
	let url = obj.url
	if (obj.params) {
		str = qs.stringify(obj.params)
		if (obj.url.indexOf('?') === -1) {
			url = obj.url + '?'
		}
	}
	let baseUrl = app.baseUrlList[0]
	return baseUrl + url + str
}
const setHead = function (carryToken = 2): HeadersInit {
	let header: HeadersInit = {}
	header['device-id'] = user.deviceId
	header['Authorization'] = 'Basic c2FiZXI6c2FiZXJfdGJrX3NlY3JldA=='
	if (isNotEmpty(user.userInfo)) {
		header['user-id'] = user.userInfo.userId
	}
	if (isNotEmpty(user.tokenCode)) {
		header['token-code'] = user.tokenCode
	} else {
		if (carryToken === 1) {
			// 需要携带token
			if (isNotEmpty(user.token)) {
				header['Blade-Auth'] = 'bearer ' + user.token
			} else {
				//toast('需要先登录')
			}
		} else if (carryToken === 2) {
			// 不做处理，有就放进去
			if (isNotEmpty(user.token)) {
				header['Blade-Auth'] = 'bearer ' + user.token
			}
		}
	}
	if (isNotEmpty(app.appId)) {
		header['app-id'] = app.appId
	}
	if (isNotEmpty(user.tenantId)) {
		header['tenant-id'] = user.tenantId
	}
	if (isNotEmpty(user.sysAppId)) {
		header['sys-app-id'] = user.sysAppId
	}
	header['trace-id'] = UUIDGeneratorBrowser().replace(/-/g, '')
	header['trace-soft-info'] = app.appName + ':' + app
		.appVersion
	if (isNotEmpty(user.userInfo)) {
        header['user-id'] = user.userInfo.userId
    }
	return header
}

const interceptor = function (response: {data?:any,code?:number}) {
	const code = response.code 
	if (code === 200) { //成功
		//logYunConsole.reqLog(false, response, _config)
		return { type: 'resolve', data: response.data }
	} else {
		//logYunConsole.reqLog(true, response, _config)
		let message = ''
		if (response.data.msg) {
			message = response.data.msg
		} else if (response.data.error_description) {
			message = response.data.error_description
		} else if (response.data.message) {
			message = response.data.message
		}
		//toast(message)
		return { type: 'reject', data: null }
	}
}

type httpOptionType = {
	url: string,
	params?: object,
	data?: object,
	method?: string,
	carryToken?: number
}
async function  fetchRequest(option: httpOptionType):Promise<any> {
	return  new Promise((resolve, reject) => {
		let data: RequestInit = {
			headers: setHead(option.carryToken),
			body: JSON.stringify(option.data),
			method: option.method,
			mode: "cors",
			//signal:option.signal
		}
		let url = setUrl(option)
		fetch(url, data)
			.then<Response>(
				(response) => response.json()
					.then<any>(res => {
						let result = interceptor(res)
						if (result.type === 'resolve') {
							resolve(res)
						}else if (result.type === 'reject') {
							reject(res)
						}
					}))
			.catch<any>(err => {
				if (err.name === 'AbortError') {
				} else {
					reject(err)
				}
			})
	}).catch(err=>{})
}
export default fetchRequest
